#ifndef _MOTOR_DRV_H
 #define _MOTOR_DRV_H
 
#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/wdt.h>
#include <avr/eeprom.h>
#include "pll_drv.h"
#include "main.h"

// ***************************************************************************************************************
//Port definitions
// ***************************************************************************************************************

// Port B
// PB7 : HS_U 	: output
// PB6 : HS_V 	: output
// PB5 : HALL_C : input
// PB4 : I_DC	: input
// PB3 : AREF/2	: input
// PB2 : HALL_A	: input
// PB1 : HS_W	: output
// PB0 : LS_W	: output

// Port C
// PC7 : SHDN 	: output
// PC6 : U_BAT 	: input
// PC5 : U_TEMP : input
// PC4 : PAS	: input (Drehmoment)
// PC3 : SDA	: output (I2C nicht genutzt)
// PC2 : SCL	: output (IC2 nicht genutzt)
// PC1 : BMS_VCC: output (GND fuer BMS)
// PC0 : LS_V	: output

// Port D
// PD7 : LED 	: output
// PD6 : HALL_B	: input
// PD5 : SS		: output  (wenn inverter SPI master ist)
// PD4 : SCK	: output  (wenn inverter SPI master ist)
// PD3 : MOSI	: output  (wenn inverter SPI master ist)
// PD2 : MISO	: input   (wenn inverter SPI master ist)
// PD1 : nc		: output
// PD0 : LS_U	: output

//motor phases
#define HS_U		(1<<7)
#define LS_U		(1<<0)
#define HS_V		(1<<6)
#define LS_V		(1<<0)
#define HS_W		(1<<1)
#define LS_W		(1<<0)

//Hall sensor input pins.
#define HALL_A 		(1<<2)
#define HALL_B 		(1<<6)
#define HALL_C 		(1<<5)

#define HALL_A_MASK ((PINB & HALL_A) >> 2)
#define HALL_B_MASK ((PIND & HALL_B) >> 5)
#define HALL_C_MASK ((PINB & HALL_C) >> 3)

//Hall sector definition (according to AVR443-  Sensor-based control of three phase BLDC.pdf", figure 2-2)
#define HAS1     5 
#define HAS2     1 
#define HAS3     3 
#define HAS4     2 
#define HAS5     6 
#define HAS6     4 

//#define BLOCK_COMMUTATION
#define BLOCK_COMMUTATION_ANGLE 40

// 64MHz (PLL frequency) / 2666 / 2 = 12 kHz (PWM frequency)
#define	MAX_PWM						2666
#define MAX_THETA					80 // equals one sixth of the circle

extern volatile unsigned int amplitude;
extern volatile unsigned int rpmCounter;
extern volatile unsigned int rpm;

extern void mdrvInit(void);
extern void pscInit(unsigned int OC);
extern void pscLoad (unsigned int DC0, unsigned int DC1,  unsigned int DC2);
extern void doSensorInterrupt(void);
				 
extern void pscStart(void);
extern void pscStop(void);
extern void hallSensorInit(void);
extern void svpwmInit(void);
extern void svpwm(unsigned short amp, unsigned char Counter_Value, unsigned char Top, unsigned char Sector);

#endif 